package com.anti.core.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.Log;
import com.anti.commom.context.constant.ConstantContext;
import com.anti.commom.enums.CommonStatusEnum;
import com.anti.jdbc.DBUtils;
import com.anti.modular.sys.consts.entity.SysConfig;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @Description 初始化常量的监听器 当spring装配好配置后，就去数据库读constants
 * @Author anTi
 * @Date 2021-3-15
 */
@Component

public class ConstantsInitListener implements ApplicationListener<ContextRefreshedEvent> {
    private static final Log log = Log.get();
    @Resource
    DBUtils dbUtils;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        /*加载数据字典到缓存*/
        loadDic();
        /*加载数据属性配置到缓存*/
        loadProps();
    }



    private void loadProps() {
        String sql="select code,value from sys_config where status = ?";
        // 获取sys_config表的数据
        List<SysConfig> configs = dbUtils.query(sql, SysConfig.class, CommonStatusEnum.ENABLE.getCode());
        // 将查询到的参数配置添加到缓存
        if (ObjectUtil.isNotEmpty(configs)) {
            configs.forEach(sysConfig ->
                    ConstantContext.putConstant(sysConfig.getCode(),sysConfig.getValue())
            );
        }
        log.info(">>> sys_config表数据已加载完成 共{}条数据",configs.size());
    }

    private void loadDic() {
        log.info(">>> 数据字典已加载完成");
    }
}
